<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import { useSnakeGame } from './hooks/useSnakeGame'

const router = useRouter()
const speed = ref(150)
const cellSize = 24
const boardSize = ref(20)
const gameContainer = ref<HTMLElement | null>(null)

async function onGameOver() {
  try {
    await ElMessageBox.alert(`游戏结束！总得分：${score.value}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '返回首页',
      showCancelButton: true,
      type: 'warning',
    })
    // resetGame()
    // startGame(onGameOver, speed.value)
  }
  catch {
    await router.push('/')
  }
}

const {
  snake,
  food,
  score,
  status,
  startGame,
  pauseGame,
  resumeGame,
  resetGame,
  setDirection,
} = useSnakeGame(boardSize.value)

function startGameWithSpeed() {
  resetGame()
  startGame(onGameOver, speed.value)
}

function handleKeyDown(e: KeyboardEvent) {
  switch (e.key) {
    case 'ArrowUp':
    case 'w':
    case 'W':
      setDirection('up')
      break
    case 'ArrowDown':
    case 's':
    case 'S':
      setDirection('down')
      break
    case 'ArrowLeft':
    case 'a':
    case 'A':
      setDirection('left')
      break
    case 'ArrowRight':
    case 'd':
    case 'D':
      setDirection('right')
      break
  }
}

onMounted(() => {
  if (gameContainer.value) {
    gameContainer.value.focus()
  }
  window.addEventListener('keydown', handleKeyDown)
})

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
})

function getCellClass(x: number, y: number) {
  if (food.value.x === x && food.value.y === y)
    return 'food'

  const head = snake.value[0]
  if (head && head.x === x && head.y === y)
    return 'snake-head'

  if (snake.value.some(seg => seg.x === x && seg.y === y))
    return 'snake'

  return ''
}
const boardStyle = computed(() => {
  const screenWidth = window.innerWidth
  const padding = 32 // 边距
  let boardWidth = boardSize.value * cellSize

  if (screenWidth < 768) {
    // 移动端宽度适配
    boardWidth = screenWidth - padding
  }

  return {
    width: `${boardWidth}px`,
    height: `${boardSize.value * cellSize}px`,
  }
})
function handleGoHome() {
  router.push('/')
}
</script>

<template>
  <div ref="gameContainer" class="snake-game" tabindex="0" @keydown="handleKeyDown">
    <div class="score">
      得分：{{ score }}
      <span v-if="!['idle', 'gameover'].includes(status)"> 当前速度： {{ speed === 80 ? '困难' : speed === 150 ? '中等' : '简单' }}</span>
    </div>

    <div class="controls">
      <el-select v-if="['idle', 'gameover'].includes(status)" v-model="speed" placeholder="选择速度" size="small" class="speed-selector">
        <el-option label="简单" :value="300" />
        <el-option label="中等" :value="150" />
        <el-option label="困难" :value="80" />
      </el-select>

      <el-button v-if="status === 'idle' || status === 'gameover'" type="primary" size="small" @click="startGameWithSpeed">
        开始游戏
      </el-button>
      <el-button v-if="status === 'running'" type="warning" size="small" @click="pauseGame">
        暂停
      </el-button>
      <el-button v-if="status === 'paused'" type="success" size="small" @click="resumeGame(speed)">
        继续
      </el-button>
      <el-button type="warning" size="small" @click="resetGame">
        重置
      </el-button>
      <el-button size="small" @click="handleGoHome">
        返回首页
      </el-button>
    </div>

    <div class="board" :style="boardStyle">
      <div
        v-for="rowIndex in boardSize"
        :key="rowIndex"
        class="row"
      >
        <div
          v-for="colIndex in boardSize"
          :key="colIndex"
          class="cell"
          :class="getCellClass(colIndex - 1, rowIndex - 1)"
          :style="{ width: `${cellSize}px`, height: `${cellSize}px` }"
        />
      </div>
    </div>

    <div class="mobile-controls">
      <el-button class="btn up" @click="setDirection('up')">
        ↑
      </el-button>
      <div class="h-controls">
        <el-button class="btn left" @click="setDirection('left')">
          ←
        </el-button>
        <el-button class="btn right" @click="setDirection('right')">
          →
        </el-button>
      </div>
      <el-button class="btn down" @click="setDirection('down')">
        ↓
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.snake-game {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  user-select: none;
  outline: none;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(42, 82, 152, 0.8);

  .score {
    font-size: 18px;
    color: #e0f7fa;
    font-weight: 600;
    margin-bottom: 12px;
  }

  .controls {
    margin-bottom: 16px;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: center;
    align-items: center;

    .speed-selector {
      min-width: 120px;
    }
  }

  .board {
    display: flex;
    flex-direction: column;
    background-color: #0d47a1;
    border: 4px solid #42a5f5;
    border-radius: 8px;
    box-shadow: inset 0 0 20px #64b5f6;
  }

  .row {
    display: flex;
  }

  .cell {
    border: 1px solid #1565c0;
    box-sizing: border-box;
    background-color: #1a237e;
    transition: background-color 0.3s ease;

    &.snake {
      background: linear-gradient(45deg, #76ff03, #c6ff00);
      box-shadow: 0 0 6px 2px #c6ff00;
    }

    &.snake-head {
      background: radial-gradient(circle at center, #00b0ff, #2962ff);
      box-shadow: 0 0 12px 5px #82b1ff;
    }

    &.food {
      background: radial-gradient(circle at center, #ff3d00, #bf360c);
      box-shadow: 0 0 10px 3px #ff3d00;
    }
  }

  .mobile-controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 16px;

    .h-controls {
      display: flex;
      justify-content: center;
      gap: 12px;
      margin: 8px 0;
    }

    .btn {
      width: 120px;
      height: 48px;
      font-size: 22px;
      padding: 0;
      font-weight: bold;
      color: #fff;
      background-color: #1565c0;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgb(21 101 192 / 0.7);
      transition: background-color 0.2s ease;
      user-select: none;

      &:hover {
        background-color: #1e88e5;
      }

      &:active {
        background-color: #0d47a1;
      }
    }
  }
}
</style>
